package com.pingba.controller;

import com.pingba.common.Constant;
import com.pingba.convert.MsgSendConvert;
import com.pingba.entity.User;
import com.pingba.entity.msg.*;
import com.pingba.executor.Station;
import com.pingba.service.msg.*;
import com.pingba.util.ReturnHelp;
import com.pingba.util.helper.JsonHelp;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/10/26 0026.
 */

@Controller
@RequestMapping(value = "/pingba/msg", method = {RequestMethod.GET, RequestMethod.POST})
public class MsgController {

    @Autowired
    private MsgSendService msgSendService;
    @Autowired
    private MsgReplyService msgReplyService;
    @Autowired
    private MsgTypeService msgTypeService;
    @Autowired
    private Station station;
    @Autowired
    private MsgSubscribeService msgSubscribeService;
    @Autowired
    private MsgApplyService msgApplyService;

    private static Logger logger = Logger.getLogger(MsgController.class);

    /**
     * @param msgSendJson MsgSend�����json��ʽ����
     * @return
     */
    @RequestMapping("send")
    @ResponseBody
    public String send(HttpSession session, @RequestParam("msgSendJson") String msgSendJson) {
        User user = (User) session.getAttribute(Constant.UserInSession);
        if (user == null) {
            return ReturnHelp.getReturnString(false, Constant.NeedLoginMsg);
        }

        logger.info("msgSendJson is: " + msgSendJson);
        MsgSend msgSend = JsonHelp.objectFromJson(msgSendJson, MsgSend.class);
        logger.info(msgSend);
        msgSend.setUserId(user.getSid());
        msgSendService.insert(msgSend);
        return ReturnHelp.getReturnString(true, Constant.SuccessMsg);

    }

    @RequestMapping("mySends")
    @ResponseBody
    public String mySends(HttpSession session) {
        User user = (User) session.getAttribute(Constant.UserInSession);
        if (user == null) {
            return ReturnHelp.getReturnString(false, Constant.NeedLoginMsg);
        }
        List<MsgSend> sendList = msgSendService.getMysends(user.getSid());
        logger.info("sendList.size is: " + sendList.size());
        return ReturnHelp.getReturnString(true, sendList);
    }

    @RequestMapping("test")
    @ResponseBody
    public String test(HttpSession session, @RequestParam("msgSendJson") String msgSendJson) {

        JsonHelp.praseTaskDataStructFromJson(msgSendJson);
        return null;
    }

    @RequestMapping("testList")
    @ResponseBody
    public String testList(HttpSession session, @RequestParam("msgSendJson") String msgSendJson) {

        List<MsgSubscribe> result = JsonHelp.praseMsgSubscribeListFromJson(msgSendJson);

        for (int i = 0; i < result.size(); i++) {
            MsgSubscribe p = result.get(i);
            System.out.println(p.toString());
        }
        return null;
    }

    @RequestMapping("msgTypes")
    @ResponseBody
    public String getMsgTypes() {
        List<MsgType> msgTypeList = msgTypeService.selectList();
        for (MsgType type : msgTypeList) {
            logger.info("type is: " + type);
        }
        return ReturnHelp.getReturnString(true, JsonHelp.jsonFromObject(msgTypeList));
    }

    /**
     * @param
     * @param msgReplyJson
     * @return
     */
    @RequestMapping("reply")
    @ResponseBody
    public String reply(HttpSession session,
                        @RequestParam("msgReplyJson") String msgReplyJson) {
        User user = (User) session.getAttribute(Constant.UserInSession);
        if (user == null) {
            return ReturnHelp.getReturnString(false, Constant.NeedLoginMsg);
        }

        logger.info(msgReplyJson);
        MsgReply msgReply = JsonHelp.objectFromJson(msgReplyJson, MsgReply.class);
        msgReply.setHaveResponse(false);
        msgReply.setReaded(false);
        msgReply.setUserId(user.getSid());
        msgReplyService.insert(msgReply);
        station.msgReply(msgReply);

        logger.info("user :" + ((User) session.getAttribute(Constant.UserInSession)).getSid() + "reply a msg:f" + msgReply);
        return ReturnHelp.getReturnString(true, "insert successful");
    }


    @RequestMapping("myReplys")
    @ResponseBody
    public String myReplys(HttpSession session) {
        User user = (User) session.getAttribute(Constant.UserInSession);
        if (user == null) {
            return ReturnHelp.getReturnString(false, Constant.NeedLoginMsg);
        }
        return null;

    }


    /**
     * 按列表模式得到附近的消息，目前按照全局查找的方式实现
     * 带完成
     * <ul>
     *     <li>分页查询</li>
     *     <li>排序类型</li>
     * </ul>
     * @param session   用来追踪用户的信息
     * @param longitude 经度
     * @param latitude  纬度
     * @param query     查询条件
     * @param page
     * @param orderType 排序类型
     * @param gender    男女类型，参考#Gender， 传递枚举值的code
     * @return
     */
    @RequestMapping("nearByList")
    @ResponseBody
    public String nearByList(HttpSession session,
                             @RequestParam("longitude") float longitude,
                             @RequestParam("latitude") float latitude,
                             @RequestParam("query") String query,
                             @RequestParam("page") int page,
                             @RequestParam("orderType") int orderType,
                             @RequestParam("gender") int gender
    ) {
        User user = (User) session.getAttribute(Constant.UserInSession);
        String userName = user != null ? user.getNickName() : "vistor";
        logger.info(userName + " check nearByList at: " + longitude + " : " + latitude + "\tquery is: " + query + " \t gender is: " + gender);
        List<MsgSend> resultList = msgSendService.nearByList(longitude, latitude, query, page, orderType, gender, user==null ? 0 : user.getSid());
        String sid = "";
        for (MsgSend temp : resultList) {
            sid = sid.concat(String.valueOf(temp.getSid())).concat(":");
        }
        logger.info("Nearby msg is: " + resultList.size() + "\n msg id: " + sid);
        return ReturnHelp.getReturnString(true, JsonHelp.jsonFromObject(resultList));
    }




    /**
     * 按照地图模式得到附近的消息，必须要给出距离
     * @param session       用来追中用户的查询
     * @param longitude     当前位置的经度
     * @param latitude      当前位置的纬度
     * @param range         多少距离内的消息（单位：米）
     * @param gender        男女类型，参考#Gender  传递枚举值的code
     * @return
     */
    @RequestMapping("nearByMap")
    @ResponseBody
    public String nearByMap(HttpSession session,
                            @RequestParam("longitude") double longitude,
                            @RequestParam("latitude") double latitude,
                            @RequestParam("range") int range,
                            @RequestParam("gender") int gender          // 性别
    ) {
        User user = (User) session.getAttribute(Constant.UserInSession);
        String userName = user != null ? user.getNickName() : "vistor";
        logger.info(userName + " check nearByMap at: "+ longitude + " : " + latitude + " \t gender is: " + gender);
        List<MsgSend> resultList = msgSendService.nearByMap(longitude, latitude, range, gender, user==null ? 0 : user.getSid());
        List<MsgSend> subscribeList = msgSubscribeService.mySubscribes(user);
        String sid = "";
        for (MsgSend temp : resultList) {
            sid = sid.concat(String.valueOf(temp.getSid())).concat(":");
        }
        logger.info("Nearby msg is: " + resultList.size() + "\n msg id: " + sid);
        return ReturnHelp.getReturnString(true, JsonHelp.jsonFromObject(MsgSendConvert.convert2List(resultList, subscribeList)));
    }


    @RequestMapping("readMsg")
    @ResponseBody
    public String readMsg(HttpSession session,
                          @RequestParam("msgSendId") long msgSendId,
                          @RequestParam("msgReplyId") long msgReplyId) {
        User user = (User) session.getAttribute(Constant.UserInSession);
        if (user == null) {
            return ReturnHelp.getReturnString(false, Constant.NeedLoginMsg);
        }
        logger.info("msgSendId is: " + msgSendId + "\tmsgReplyId is: " + msgReplyId);

        if (msgSendId != 0) {
            MsgSend msgSend = msgSendService.selectById(msgSendId);
            if (msgSend == null) {
                logger.warn("can't find any msgSend of " + msgSendId);
                return ReturnHelp.getReturnString(false, "can't find msgSend of " + msgSendId);
            }
            station.msgRead(msgSend);
        }
        if (msgReplyId != 0) {
            MsgReply msgReply = msgReplyService.selectById(msgReplyId);
            if (msgReply == null) {
                logger.warn("can't find any msgReply of " + msgReplyId);
                return ReturnHelp.getReturnString(false, "can't find msgReply of " + msgReplyId);
            }
            station.msgRead(msgReply);
        }
        return ReturnHelp.getReturnString(true, Constant.SuccessMsg);
    }


// 任务处理的开始

    /**
     * 我的收藏
     *
     * @param session
     * @return
     */
    @RequestMapping("mySubscribe")
    @ResponseBody
    public String mySubscribe(HttpSession session) {
        User user = (User) session.getAttribute(Constant.UserInSession);
        if (user == null) {
            return ReturnHelp.getReturnString(false, Constant.NeedLoginMsg);
        }
        List<MsgSend> mySubscribe = msgSubscribeService.mySubscribes(user);
        System.out.println(mySubscribe.size());
        return ReturnHelp.getReturnString(true, JsonHelp.jsonFromObject(mySubscribe));
    }

    /**
     * 收藏别人发送的msgSend
     *
     * @param session
     * @param msgSendId 别人发送的msgSend的id
     * @return
     */
    @RequestMapping("addSubscribe")
    @ResponseBody
    public String addSubscribe(HttpSession session,
                               @RequestParam("msgSendId") long msgSendId) {
        User user = (User) session.getAttribute(Constant.UserInSession);
        if (user == null) {
            return ReturnHelp.getReturnString(false, Constant.NeedLoginMsg);
        }
        MsgSubscribe subscribe = MsgSubscribe.getOne(user.getSid(), msgSendId);
        msgSubscribeService.subscribeOne(subscribe);
        return ReturnHelp.getReturnString(true, Constant.SuccessMsg);
    }

    /**
     * 取消对本条消息的收藏
     *
     * @param session
     * @param msgSendId 别人发的msgSend的id
     * @return
     */
    @RequestMapping("unSubscribe")
    @ResponseBody
    public String unSubscribe(HttpSession session,
                              @RequestParam("msgSendId") long msgSendId) {
        User user = (User) session.getAttribute(Constant.UserInSession);
        if (user == null) {
            logger.info("unSubscribe need login");
            return ReturnHelp.getReturnString(false, Constant.NeedLoginMsg);
        }
        msgSubscribeService.unSubscribeOne(user.getSid(), msgSendId);
        return ReturnHelp.getReturnString(true, Constant.SuccessMsg);
    }


    /**
     * 对msgSend活动的申请
     *
     * @param session
     * @param msgSendId
     * @param msgOwnerId
     * @param applicationContent
     * @return
     */
    @RequestMapping("msgApply")
    @ResponseBody
    public String msgApply(HttpSession session,
                           @RequestParam("msgSendId") long msgSendId,
                           @RequestParam("msgOwnerId") long msgOwnerId,
                           @RequestParam("applicationContent") String applicationContent
    ) {
        User user = (User) session.getAttribute(Constant.UserInSession);
        if (user == null) {
            return ReturnHelp.getReturnString(false, Constant.NeedLoginMsg);
        }
        MsgApply apply = MsgApply.getTemplate(user, msgSendId, msgOwnerId, applicationContent);
        logger.info("msg apply is:" + apply);
        msgApplyService.insert(apply);
        return ReturnHelp.getReturnString(true, Constant.SuccessMsg);
    }

    /**
     * 同意别人的申请
     *
     * @param session
     * @param msgApplyId
     * @return
     */
    @RequestMapping("msgApplyAgree")
    @ResponseBody
    public String msgApplyAgree(HttpSession session,
                                @RequestParam("msgApplyId") long msgApplyId
    ) {
        User user = (User) session.getAttribute(Constant.UserInSession);
        if (user == null) {
            return ReturnHelp.getReturnString(false, Constant.NeedLoginMsg);
        }
        MsgApply apply = new MsgApply();
        apply.setSid(msgApplyId);
        apply.setStatus(MsgApply.ApplyAgree);
        apply.setHandleTime(new Date().getTime());
        msgApplyService.agree(apply);
        return ReturnHelp.getReturnString(true, Constant.SuccessMsg);
    }

    /**
     * 拒绝别人的申请
     *
     * @param session
     * @param msgApplyId msgApply的id
     * @return
     */
    @RequestMapping("msgApplyRefuse")
    @ResponseBody
    public String msgApplyRefuse(HttpSession session,
                                 @RequestParam("msgApplyId") long msgApplyId
    ) {
        User user = (User) session.getAttribute(Constant.UserInSession);
        if (user == null) {
            return ReturnHelp.getReturnString(false, Constant.NeedLoginMsg);
        }
        MsgApply apply = new MsgApply();
        apply.setSid(msgApplyId);
        apply.setStatus(MsgApply.ApplyRefuse);
        apply.setHandleTime(new Date().getTime());
        msgApplyService.refuse(apply);
        return ReturnHelp.getReturnString(true, Constant.SuccessMsg);
    }

    @RequestMapping("msgApply2me")
    @ResponseBody
    public String msgApply2me(HttpSession session) {
        User user = (User) session.getAttribute(Constant.UserInSession);
        if (user == null) {
            return ReturnHelp.getReturnString(false, Constant.NeedLoginMsg);
        }
        station.readMsgApply(user);
        Map<Long, Map<String, Object>> result = msgSendService.myMsgWithApply(user);
        return ReturnHelp.getReturnString(true, JsonHelp.jsonFromObject(result));
    }


    /**
     * 检查用户是否有新的msgapply的请求，供客户端在菜单栏推送消息
     * @param session session信息
     * @return true，object是否为null
     */
    @RequestMapping("newMsgApply2me")
    @ResponseBody
    public String newMsgApply2me(HttpSession session) {
        User user = (User) session.getAttribute(Constant.UserInSession);
        if (user == null) {
            return ReturnHelp.getReturnString(false, Constant.NeedLoginMsg);
        }
        Map<Long, Map<String, Object>> result = msgSendService.newMyMsgWithApply(user);
        //去除新的标志位
        msgApplyService.setReaded(user);
        return ReturnHelp.getReturnString(true, JsonHelp.jsonFromObject(result));
    }

    @RequestMapping("myMsgApply")
    @ResponseBody
    public String myMsgApply(HttpSession session) {
        User user = (User) session.getAttribute(Constant.UserInSession);
        if (user == null) {
            return ReturnHelp.getReturnString(false, Constant.NeedLoginMsg);
        }
        Map<Long, Map<String, Object>> result = msgApplyService.myApplies(user);
        return ReturnHelp.getReturnString(true, JsonHelp.jsonFromObject(result));
    }

    /**
     * 删除我的msgApply
     * @param session
     * @param msgApplyId
     * @return
     */
    @RequestMapping("deleteMyMsgApply")
    @ResponseBody
    public String deleteMyMsgApply(HttpSession session, @RequestParam("msgApplyId") long msgApplyId) {
        User user = (User) session.getAttribute(Constant.UserInSession);
        if (user == null) {
            return ReturnHelp.getReturnString(false, Constant.NeedLoginMsg);
        }
        msgApplyService.deleteMyMsgApply(msgApplyId, user.getSid());
        logger.info("userId:" + user.getSid() + " delete msgApply, id:" + msgApplyId);
        return ReturnHelp.getReturnString(true, Constant.SuccessMsg);
    }

    /**
     * 删除用户发送的msgsend，同时会删除其他用户对该条消息的请求
     * @param session session信息,客户端不需要传递
     * @param msgSendId 用户发送的id
     * @return
     */
    @RequestMapping("deleteMyMsgSend")
    @ResponseBody
    public String deleteMyMsgSend(HttpSession session, @RequestParam("msgSendId") long msgSendId) {
        User user = (User) session.getAttribute(Constant.UserInSession);
        if (user == null) {
            return ReturnHelp.getReturnString(false, Constant.NeedLoginMsg);
        }
        logger.info("userId:"+ user.getSid() + " delete msgSend, id:" + msgSendId);
        msgSendService.deleteMsgSend(msgSendId, user.getSid());
        return ReturnHelp.getReturnString(true, Constant.SuccessMsg);
    }


    /**
     * 只给看最近发送的10条消息
     * @param userId    被查看用户的id
     * @return
     */
    @RequestMapping("userMsgSend")
    @ResponseBody
    public String userMsgSend(HttpSession session, @RequestParam("userId") long userId) {
        User user = (User) session.getAttribute(Constant.UserInSession);
        String userName = user == null ? "vistor" : user.getNickName();
        logger.info(userName + "check recent send msg of user: " + userId  + "at: " + new Date());
        List<MsgSend> recents = msgSendService.recentSend(userId);
        return ReturnHelp.getReturnString(true, JsonHelp.jsonFromObject(recents));

    }

}
